<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script>
    const PENDING = 'pending'
    const FULFILLED = 'fulfilled'
    const REJECTED = 'rejected'
    class AggregateError extends Error {
        constructor(errors, message) {
            super(message);
            this.name = 'AggregateError';
            this.errors = errors;
        }
    }
    class MyPromise {
        #state = PENDING
        #result = undefined
        #handler = []
        constructor(executor) {
            const resolve = (data) => {
                this.#changeState(FULFILLED, data)
            }
            const reject = (reson) => {
                this.#changeState(REJECTED, reson)
            }
            // 只能捕获同步错误，无法捕获异步错误
            try {
                executor(resolve, reject)
            } catch (error) {
                reject(error)
            }
        }
        #isPormiseLike (value) {
            if (value !== null && (typeof value === 'object' ||  typeof value === 'function')) {
                return typeof value.then === 'function'
            }
            return false
        }
        #runMicorTask(fun) {
            if (typeof MutationObserver === 'function') {
                const ob = new MutationObserver(fun)
                const textNode = document.createTextNode('1')
                ob.observe(textNode, {
                    characterData: true
                })
                textNode.data = 2
            } else {
                setTimeout(fun, 0);
            }
        }
        #runOne(callback, resolve, reject) {
            this.#runMicorTask(() => {
                if (typeof callback !== 'function') {
                    const settled = this.#state === FULFILLED ? resolve : reject
                    settled(this.#result)
                    return
                }
                try {
                    const data = callback(this.#result)
                    if (this.#isPormiseLike(data)) {
                        data.then(resolve, reject)
                    } else {
                        resolve(data)
                    }
                } catch (error) {
                    reject(error)
                }
            })
        }
        #run() {
            if (this.#state === PENDING) return
            while (this.#handler.length) {
                const { onFulfilled, onRejected, resolve, reject } = this.#handler.shift()
                if (this.#state === FULFILLED) {
                    this.#runOne(onFulfilled, resolve, reject)
                } else {
                    this.#runOne(onRejected, resolve, reject)
                }
            }
        }
        #changeState(state, result) {
            if (this.#state !== PENDING) return
            this.#state = state
            this.#result = result
            this.#run()
        }
        then (onFulfilled, onRejected) {
            return new MyPromise((resolve, reject) => {
                this.#handler.push({
                    onFulfilled,
                    onRejected,
                    resolve,
                    reject
                })
                this.#run()
            })
        }
        // Promise 实例的 catch() 方法用于注册一个在 promise 被拒绝时调用的函数。
        // 它会立即返回一个等效的 Promise 对象，这可以允许你链式调用其他 promise 的方法。此方法是
        catch (onRejected) {
            return this.then(undefined , onRejected)
        }
        // Promise 实例的 finally() 方法用于注册一个在 promise 敲定（兑现或拒绝）时调用的函数。它会立即返回一个等效的 Promise 对象
        finally (onFinally) {
            return this.then(data => {
                onFinally()
                return data
            }, err => {
                onFinally()
                throw err
            })
        }
        // Promise.all() 静态方法接受一个 Promise 可迭代对象作为输入，并返回一个 Promise。
        // 当所有输入的 Promise 都被兑现时，返回的 Promise 也将被兑现（即使传入的是一个空的可迭代对象），
        // 并返回一个包含所有兑现值的数组。如果输入的任何 Promise 被拒绝，则返回的 Promise 将被拒绝，并带有第一个被拒绝的原因。
        static all (proms) {
            let _resolve,_reject
            const p = new MyPromise((resolve, reject) => {
                _resolve = resolve
                _reject = reject
            })
            let count = 0
            let result = []
            let fulfilledCount = 0
            // 遍历迭代器
            for (const prom of proms) {
                const i = count
                count ++
                MyPromise.resolve(prom).then(data => {
                    // 将成功的数据汇总到result
                    result[i] = data
                    // 判断是不是全部完成了
                    fulfilledCount ++ 
                    if (fulfilledCount === count) {
                        _resolve(result)
                    }
                } , err => _reject(err))
            }
            if (count === 0) {
                return result
            }
            return p 
        }
        // 静态方法将给定的值转换为一个 Promise。如果该值本身就是一个 Promise，
        // 那么该 Promise 将被返回；如果该值是一个 thenable 对象，Promise.resolve() 
        // 将调用其 then() 方法及其两个回调函数；否则，返回的 Promise 将会以该值兑现。
        static resolve (value) {
            // 如果该值本身就是一个 Promise，那么该 Promise 将被返回
            if (value instanceof MyPromise) return value
            let _resolve,_reject;
            const p = new MyPromise((resolve, reject) => {
                _resolve = resolve
                _reject = reject
            })
            // 如果该值是一个 thenable 对象，Promise.resolve() ,将调用其 then() 方法及其两个回调函数
            if (p.#isPormiseLike(value)) {
                value.then(_resolve, _reject)
            }
            // 否则，返回的 Promise 将会以该值兑现。
            else {
                _resolve(value)
            }
            return p
        }
        // Promise.reject() 静态方法返回一个已拒绝（rejected）的 Promise 对象，拒绝原因为给定的参数。
        static reject (reason) {
            return new MyPromise((resolve, reject) => {
                reject(reason)
            })
        }
        // Promise.allSettled() 静态方法将一个 Promise 可迭代对象作为输入，
        // 并返回一个单独的 Promise。当所有输入的 Promise 都已敲定时（包括传入空的可迭代对象时），
        // 返回的 Promise 将被兑现，并带有描述每个 Promise 结果的对象数组。
        static allSettled (proms) {
            let _resolve,_reject
            const p = new MyPromise((resolve, reject) => {
                _resolve = resolve
                _reject = reject
            })
            let results = [];
            let completed = 0;
            let count = 0
            for (const prom of proms) {
                const i = count
                count ++
                MyPromise.resolve(prom).then(data => {
                    results[i] = {
                        status: FULFILLED,
                        value: data
                    }
                    completed ++
                    if (completed === count) {
                        _resolve(results)
                    }
                }, err => {
                    results[i] = {
                        status: REJECTED,
                        reason: err
                    }
                    completed ++
                    if (completed === count) {
                        _resolve(results)
                    }
                })
            }
            if (count === 0) {
                return results
            }
            return p
        }
        
        // Promise.any() 静态方法将一个 Promise 可迭代对象作为输入，并返回一个 Promise。
        // 当输入的任何一个 Promise 兑现时，这个返回的 Promise 将会兑现，并返回第一个兑现的值。
        // 当所有输入 Promise 都被拒绝（包括传递了空的可迭代对象）时，它会以一个包含拒绝原因数组的 AggregateError 拒绝。
        static any (proms) {
            let _resolve,_reject
            const p = new MyPromise((resolve, reject) => {
                _resolve = resolve
                _reject = reject
            })
            let errs = []
            let hasReolved = false
            let count = 0
            let completed = 0
            for (const prom of proms) {
                const i = count
                count ++
                MyPromise.resolve(prom).then(res => {
                    if (!hasReolved) {
                        hasReolved = true
                        _resolve(res)
                    }
                }, err => {
                    errs[i] = err
                    completed ++ 
                    if (completed === count) {
                       console.log('dayin',new AggregateError(errs, 'All promises were rejected'))
                    }
                })
            }
            return p
        }
        // Promise.race() 静态方法接受一个 promise 可迭代对象作为输入，并返回一个 Promise。
        // 这个返回的 promise 会随着第一个 promise 的敲定而敲定。
        static race (proms) {
            return new MyPromise((resolve, reject) => {
                for (const prom of proms) {
                    MyPromise.resolve(prom).then(res => {
                        resolve(res)
                    }, err => {
                        reject(err)
                    })
                }
            })
        }
        // 实现 Promise.withResolvers 方法
        // Promise.withResolvers 是一个静态方法，用来创建一个 Promise 对象，同时返回能够手动控制其状态的 
        // resolve 和 reject 方法。这个功能在一些特定场景下非常有用，例如需要在异步操作中手动控制 Promise 状态的情况
        static withResolvers() {
            let resolve, reject;
            const promise = new MyPromise((res, rej) => {
                resolve = res;
                reject = rej;
            });
            return { promise, resolve, reject };
        }
    }
   // 示例用法
    const p1 = new MyPromise((resolve, reject) => {
        setTimeout(() => {
            resolve('Resolved Promise 1');
        }, 1000);
    });

    const p2 = new MyPromise((resolve, reject) => {
        setTimeout(() => {
            resolve('Resolved Promise 2');
        }, 500);
    });

    const p3 = new MyPromise((resolve, reject) => {
  
            resolve('Resolved Promise 3');

    });
    const p = new MyPromise()
    console.log('p', p)
</script>
<body>
    
</body>
</html>l